#!/usr/bin/env python
# -*- coding: utf-8 -*-

from utils import log

from sqlalchemy.orm import mapper, sessionmaker
from sqlalchemy import Table, MetaData, Column, ForeignKey, Integer, Float, Boolean, String, Unicode, UnicodeText, \
    DateTime, UniqueConstraint
from controls.data_pool_mysql import engine

Session = sessionmaker()
Session.configure(bind=engine)

"""card_img collection has
    cardid:          卡牌id (int)
    imgid:           图片id (int)
"""

card_img_table_dict = {}


class CardImgTables(object):
    def make_table(self, p_cityid):
        if p_cityid in card_img_table_dict:
            return card_img_table_dict[p_cityid]

        class CardImgItem(object):
            def __init__(self, p_cityid):
                self.cityid = p_cityid

            def to_dict(self):
                res = {}
                res['cardid'] = self.cardid
                res['imgid'] = self.imgid
                return res

            def to_min_dict(self):
                res = {}
                res['url'] = self.imgid
                return res

            def __repr__(self):
                return "%d" % (self.cardid)

        metadata = MetaData()
        card_img_table = Table(
            'card_img_' + str(p_cityid), metadata,
            Column('id', Integer, primary_key=True),
            Column('cardid', Integer, nullable=False),
            Column('imgid', Integer, nullable=False),
            UniqueConstraint('cardid', name='uix_cardid')
        )
        mapper(CardImgItem, card_img_table)
        table = {
            'metadata': metadata,
            'table': card_img_table,
            'class': CardImgItem
        }
        card_img_table_dict[p_cityid] = table
        return table


def create_card_img_table_if_not_exist(p_cityid):
    table = CardImgTables().make_table(p_cityid)
    table['metadata'].create_all(engine)


# add a img for a card
def add_card_img_item(p_cityid, p_item):
    table = CardImgTables().make_table(p_cityid)
    item = table['class'](p_cityid)
    item.cardid = p_item['cardid']
    item.imgid = p_item['imgid']
    try:
        session = Session()
        session.add(item)
        session.flush()
        session.commit()
        return True
    except Exception, e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


# update a img for a card
def update_card_img_item(p_cityid, p_item):
    if not (p_cityid and p_item):
        return False
    table = CardImgTables().make_table(p_cityid)
    try:
        updateField = {
            table['class'].imgid: p_item['imgid']
        }
        session = Session()
        session.query(table['class']).filter(
            table['class'].cardid == p_item['cardid']).update(updateField, synchronize_session=False)
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


# delete a img for a card
def delete_card_img_item(p_cityid, p_item):
    if not (p_cityid and p_item):
        return False
    table = CardImgTables().make_table(p_cityid)
    try:
        session = Session()
        session.query(table['class']).filter(
            table['class'].cardid == p_item['cardid']).delete()
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


# batch insert
# add imgs for a city's all cards
def add_card_img_dict(p_cityid, p_card_list):
    table = CardImgTables().make_table(p_cityid)
    res = {'ok': True}

    try:
        session = Session()
        for p_item in p_card_list:
            item = table['class'](p_cityid)
            item.cardid = p_dict['cardid']
            item.imgid = p_item['imgid']
            session.add(item)
            session.flush()
            res[p_item['cardid']] = True
    except Exception, e:
        res['ok'] = False
        log.exp(e)
        session.rollback()
    finally:
        session.commit()
        session.close()
    return res


# get all cards's imgs
def get_card_img_all(p_cityid):
    try:
        session = Session()
        table = CardImgTables().make_table(p_cityid)
        items = session.query(table['class']).filter_by().all()  # .order_by(table['class'].cardid.asc())
        if not items:
            return None
        imgid_list = []
        res_raw = {}
        for item in items:
            res_raw[item.cardid] = item.imgid
            imgid_list.append(item.imgid)
        res = {
            'imgid_list': imgid_list,
            'cardid_list': res_raw.keys(),
            'res': res_raw
        }
        return res
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()


# get a cards's img
def get_card_img_by_cardid(p_cityid, p_cardid):
    try:
        session = Session()
        table = CardImgTables().make_table(p_cityid)
        item = session.query(table['class']).filter_by(cardid=p_cardid).first()
        res = item.to_dict() if item else None
        return res
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()


if __name__ == "__main__":
    create_card_img_table_if_not_exist(1)
    '''
    test_city = 1
    test_item_dict = {
            'cardid': 2,
            'imgs' : [
                {
                    'imgid': 100000024,
                    'num': 0,
                },
                {
                    'imgid': 100000025,
                    'num': 1,
                },
                {
                    'imgid': 100000026,
                    'num': 2,
                },
            ],
        }
    #add_card_img_item(test_city, test_item_0)
    #add_card_img_item(test_city, test_item_1)
    print add_card_img_dict(test_city, test_item_dict)
    print get_card_img_all(test_city)
    '''
